package com.firstgroup.dms.service.impl;

import com.firstgroup.dms.common.Result;
import com.firstgroup.dms.mapper.DrugInformationMapper;
import com.firstgroup.dms.mapper.ProcurementMapper;
import com.firstgroup.dms.mapper.SaleMapper;
import com.firstgroup.dms.pojo.DrugCategory;
import com.firstgroup.dms.pojo.DrugInformation;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DrugInformationServiceImpl {

    @Resource
    private DrugInformationMapper drugInformationMapper;

    @Resource
    private ProcurementMapper procurementMapper;

    @Resource
    private SaleMapper saleMapper;

    public Result<List<DrugInformation>> getAllDrugs() {
        try {
            List<DrugInformation> drugs = drugInformationMapper.getAllDrugs();
            System.out.println("查询到的药品数量: " + (drugs != null ? drugs.size() : 0));
            return Result.success(drugs);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取药品列表失败：" + e.getMessage());
        }
    }

    public Result<List<DrugCategory>> getAllCategories() {
        try {
            List<DrugCategory> categories = drugInformationMapper.getAllCategories();
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取药品类别失败：" + e.getMessage());
        }
    }

    public Result<Boolean> insertDrug(DrugInformation drug) {
        try {
            int result = drugInformationMapper.insertDrug(drug);
            return result > 0 ? Result.success(true) : Result.error("添加药品失败");
        } catch (Exception e) {
            return Result.error("添加药品失败：" + e.getMessage());
        }
    }

    public Result<Boolean> deleteDrug(Integer id) {
        try {
            int result = drugInformationMapper.deleteDrug(id);
            return result > 0 ? Result.success(true) : Result.error("删除药品失败");
        } catch (Exception e) {
            return Result.error("删除药品失败：" + e.getMessage());
        }
    }

    public Result getDrugById(Integer id) {
        try {
            DrugInformation drug = drugInformationMapper.selectById(id);
            if (drug == null) {
                return Result.error("药品不存在");
            }

            // 计算当前库存
            Integer inStock = procurementMapper.getInStockQuantity(id); // 入库数量
            Integer outStock = saleMapper.getOutStockQuantity(id); // 出库数量

            drug.setStock(inStock - outStock); // 设置当前库存

            return Result.success(drug);
        } catch (Exception e) {
            return Result.error("获取药品信息失败：" + e.getMessage());
        }
    }
}